package com.scfinance.SPD.service;

import com.alibaba.fastjson.JSONObject;
import com.scfinance.SPD.OutputmwApplication;
import com.scfinance.SPD.dao.OrderDaoImpl;
import com.scfinance.SPD.encrypt.DataEncrypt;
import com.scfinance.SPD.entity.UploadAppReq;
import com.scfinance.SPD.externalReq.SPDBankPAD;
import com.scfinance.SPD.tools.Comm;
import com.scfinance.SPD.tools.Pinyin;
import com.scfinance.SPD.util.*;
import com.scfinance.SPD.util.http.HttpRequester;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by admin on 2017/7/14.
 */
@Service
public class SPDUploadService extends SPDSimpleService {

    @Autowired
    private OrderDaoImpl orderDao;

    private Logger logger = LoggerFactory.getLogger(SPDUploadService.class);

    private static final String SERVICE_GETAPPID_METHOD = "getAppid";

    private static final String SERVICE_UPLOADAPPLICATION_METHOD = "uploadApplication";

    public String getAppid(String loanOrderId) {
        String appId = null;
        try {
            String method = SERVICE_GETAPPID_METHOD;
            JSONObject json = new JSONObject();
            String requestData = DataEncrypt.initialized().encrypt(method, json, "1");
            logger.info("订单" + loanOrderId + "------获取申请Id");
            System.out.println("订单" + loanOrderId + "------获取申请Id");
            String s = SPDBankPAD.sendReq(PropsUtil.getProperty("SPDURL") + Constants.UPLOADAPPLICATION_SERVER, requestData);
            String result = DataEncrypt.initialized().deEncrypt(s);
            JSONObject appidResult = (JSONObject) JSONObject.parse(result);
            logger.info("订单" + loanOrderId + "------获取申请Id，返回" + appidResult);
            System.out.println("订单" + loanOrderId + "------获取申请Id，返回" + appidResult);
            appId = null;
            if (appidResult.containsKey("appid")) {
                appId = appidResult.getString("appid");
            }
            if (Validator.isNotNull(appId)){
                Boolean returnFlag = orderDao.saveAppID(appId, loanOrderId);
                logger.info("更新发送的订单的浦发银行代码__" + (returnFlag ? "成功" : "失败"));
                System.out.println("更新发送的订单的浦发银行代码__" + (returnFlag ? "成功" : "失败"));
            }else {
                logger.info("订单" + loanOrderId + "没有发送:没有取得appId");
            }
        } catch (Exception e) {
            logger.info("订单" + loanOrderId + "------获取申请Id，失败" + e);
            System.out.println("订单" + loanOrderId + "------获取申请Id，失败" + e);
            Object[] params = {Constants.EXCEPTIONFLAG, loanOrderId};     //Exception 状态
            updateSingleFlag(params);
            setSPDOutputDefault(loanOrderId);
            e.printStackTrace();
        }
        return appId;
    }

    public String uploadApplication(String appId, Map<String, Object> map, String loanOrderId) {
        String uploadApplicationResult = null;
        try {
            String method = SERVICE_UPLOADAPPLICATION_METHOD;
            UploadAppReq uploadAppReq = buildUploadAppReq(appId, map);
            JSONObject json = (JSONObject) JSONObject.toJSON(uploadAppReq);

            logger.info("订单" + loanOrderId + "------申请件，发送" + json);
            System.out.println("订单" + loanOrderId + "------申请件，发送" + json);

            String requestData = DataEncrypt.initialized().encrypt(method, json, "1");
            String s = SPDBankPAD.sendReq(PropsUtil.getProperty("SPDURL") + Constants.UPLOADAPPLICATION_SERVER, requestData);
            uploadApplicationResult = DataEncrypt.initialized().deEncrypt(s);

            logger.info("订单" + loanOrderId + "------上传，返回" + uploadApplicationResult);
            System.out.println("订单" + loanOrderId + "------上传，返回" + uploadApplicationResult);

            JSONObject returnJson = JSONObject.parseObject(uploadApplicationResult).getJSONObject("sysres");
            logger.info("保存浦发返回信息 开始：" + loanOrderId);
            System.out.println("保存浦发返回信息 开始：" + loanOrderId);
            saveSPDReturn(appId, map, loanOrderId, returnJson);
            logger.info("保存浦发返回信息 结束：" + loanOrderId);
            System.out.println("保存浦发返回信息 结束：" + loanOrderId);
        } catch (Exception e) {
            Object[] params = {Constants.EXCEPTIONFLAG, loanOrderId};     //Exception 状态
            updateSingleFlag(params);
            setSPDOutputDefault(loanOrderId);
            e.printStackTrace();
        }
        return uploadApplicationResult;
    }

    public JSONObject searchStayPatch() {
        JSONObject returnJson = new JSONObject();
        try {
            String method = "staypatch";
            JSONObject json = new JSONObject();
            json.put("type", "02");
            json.put("source", "YCQC");
//            Date dNow = new Date();
//            Date startDate = new Date();
//            Calendar calendar = Calendar.getInstance();
//            calendar.setTime(dNow);
//            calendar.add(Calendar.DAY_OF_MONTH, -Integer.parseInt(PropsUtil.getProperty("stayPatch_day")));
//            startDate = calendar.getTime();
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
//            String searchDateFrom = sdf.format(startDate);
//            String searchDateTo = sdf.format(dNow);
            json.put("startdate", "20170921"); //2017/12/04 暂时应对查询不到的BUG
//            json.put("enddate", searchDateTo);
            logger.info("待补件查询传入参数" + json);
            System.out.println("待补件查询传入参数" + json);
            String requestData = DataEncrypt.initialized().encrypt(method, json, "0");
            String s = SPDBankPAD.sendReq(Constants.SPDURL_UAT + Constants.UPLOADAPPLICATION_SERVER, requestData);
            String str = URLDecoder.decode(DataEncrypt.initialized().deEncrypt(s), "utf-8");

            returnJson = JSONObject.parseObject(str);
            logger.info("待补件查询返回信息" + returnJson);
            System.out.println("待补件查询返回信息" + returnJson);
        } catch (Exception e) {
            returnJson.put("recordamount", 0);
            logger.info("------查询待补件，出错" + e);
            e.printStackTrace();
        }
        return returnJson;
    }

    public List<Map<String, Object>> getCustomerApp() {
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        mapList = orderDao.getCustomerApp();
        return mapList;
    }

    public List<Map<String, Object>> needAppId() {
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        mapList = orderDao.needAppId();
        return mapList;
    }

    public Boolean updateStayPatchFlag(Object[] params) {
        Boolean returnFlag = true;
        Object[] findParams = {params[1]};
        Map resultMap = orderDao.findMiniStatus(findParams);
        if (Validator.isNotNull(resultMap) && Validator.isNotNull(resultMap.get("value")) && "2".equals(String.valueOf(resultMap.get("value")))) {
            returnFlag = orderDao.updateSingleFlag(params);
            setSPDOutputDefault((String) params[1]);
            logger.info("更新发送的订单状态__" + (returnFlag ? "成功" : "失败"));
            System.out.println("更新发送的订单状态__" + (returnFlag ? "成功" : "失败"));
        }
        return returnFlag;
    }

    private UploadAppReq buildUploadAppReq(String appId, Map<String, Object> map) {
        UploadAppReq req = new UploadAppReq();

        req.setShenqingshucode(appId);
        if ("VISA新金卡".equals(map.get("productname"))) {
            req.setShenqingkaproduct("0053");
            req.setCardlayoutnumber("001");
            req.setProductname("VISA新金卡");
        } else if ("财星金卡-赵公明".equals(map.get("productname"))) {
            req.setShenqingkaproduct("0083");
            req.setCardlayoutnumber("039");
            req.setProductname("财星金卡-赵公明");
        } else if ("标准IC信用卡金卡".equals(map.get("productname"))) {
            req.setShenqingkaproduct("1002");
            req.setCardlayoutnumber("001");
            req.setProductname("标准IC信用卡金卡");
        }
        req.setShenqingrenzhongwenminchen(cutString((String) map.get("shenqingrenzhongwenminchen"), 30));
        req.setShenqingrenpinyin(cutString(Pinyin.convertName((String) map.get("shenqingrenzhongwenminchen")), 29));
        req.setShenqingrenenglishname(cutString(Pinyin.getEnglishName((String) map.get("shenqingrenzhongwenminchen")), 29));
        req.setShenqingrentuziname(cutString(Pinyin.getUpEname((String) map.get("shenqingrenzhongwenminchen")), 26));
        req.setShengqingrencardnumber(cutString((String) map.get("shengqingrencardnumber"), 18));
        String iDLimitDate = (String) map.get("certificatelimit");
        if ("长期".equals(iDLimitDate)) iDLimitDate = "20991231";
        req.setCertificatelimit(cutString(iDLimitDate, 8));
        req.setShenqingrensex(cutString(Comm.convertSex((String) map.get("shengqingrencardnumber")), 1));
        req.setShenqingrenbirthdate(cutString(Comm.getBirthday((String) map.get("shengqingrencardnumber")), 8));
        req.setShenqingrenmaritalstatus(cutString((String) map.get("shenqingrenmaritalstatus"), 1));
        req.setShenqingrenlevelofducation(cutString((String) map.get("shenqingrenlevelofducation"), 1));
        req.setFamliyhousestatus(cutString((String) map.get("famliyhousestatus"), 1));
        req.setJinjiantype("PQY9");
        req.setVipname("益车金融");
        req.setShenqingrenemail(cutString((String) map.get("shenqingrenemail"), 40));
        req.setShenqignrenfamliyareacode(cutString((String) map.get("shenqignrenfamliyareacode"), 4));
        req.setShenqingrenfamliytel(cutString((String) map.get("shenqingrenfamliytel"), 17));
        req.setShenqingrenmobilenumber(cutString((String) map.get("shenqingrenmobilenumber"), 11));
        req.setGongsizhongwenname(cutString((String) map.get("gongsizhongwenname"), 30));
        req.setGongsizhiwu(cutString((String) map.get("gongsizhiwu"), 20));
        req.setShenqingrenzhiye("205");
        req.setGongsiindustrytype("0990");
        req.setGongsiproperties("5");
        req.setGongsitelareacode(cutString((String) map.get("gongsitelareacode"), 4));
        req.setGongsitel(cutString((String) map.get("gongsitel"), 17));

        BigDecimal income = new BigDecimal((String) map.get("shenqingrenincome"));
        DecimalFormat dfIncome = new DecimalFormat("0");
        req.setShenqingrenincome(cutString(income.compareTo(new BigDecimal("10000")) == 1 ?
                dfIncome.format(income) : dfIncome.format(income.multiply(new BigDecimal("10000"))), 11));
        req.setGongsiserviceyears(cutString((String) map.get("gongsiserviceyears"), 4));
        req.setGongsiaddressarea1(cutString((String) map.get("gongsiaddressarea1"), 40));
        req.setGongsiaddressarea2(cutString((String) map.get("gongsiaddressarea2"), 40));
        req.setGongsiaddressarea3(cutString((String) map.get("gongsiaddressarea3"), 40));
        req.setSpare_filed1("0");
        req.setGongsipostcode(cutString((String) map.get("gongsipostcode"), 6));
        req.setFamliyaddresszone1(cutString((String) map.get("famliyaddresszone1"), 40));
        req.setFamliyaddresszone2(cutString((String) map.get("famliyaddresszone2"), 40));
        req.setFamliyaddresszone3(cutString((String) map.get("famliyaddresszone3"), 40));
        req.setSpare_filed2("0");
        req.setFamliypostcode(cutString((String) map.get("famliypostcode"), 6));
        req.setCardexpressaddress(cutString((String) map.get("cardexpressaddress"), 1));
        req.setZhixiqinshuname(cutString((String) map.get("zhixiqinshuname"), 30));
        if ("爸爸" == map.get("zhixiqinshurelation") || "妈妈" == map.get("zhixiqinshurelation")) {
            req.setZhixiqinshurelation("P");
        } else if ("儿子" == map.get("zhixiqinshurelation") || "女儿" == map.get("zhixiqinshurelation")) {
            req.setZhixiqinshurelation("F");
        } else if ("配偶" == map.get("zhixiqinshurelation")) {
            req.setZhixiqinshurelation("M");
        } else {
            req.setZhixiqinshurelation("B");
        }
        req.setZhixiqinshutelareacode(cutString((String) map.get("zhixiqinshutelareacode"), 4));
        req.setZhixiqinshutel(cutString((String) map.get("zhixiqinshutel"), 17));
        req.setZhixiqinshumobilephone(cutString((String) map.get("zhixiqinshumobilephone"), 11));
        req.setQfishaschild(cutString((String) map.get("qfishaschild"), 1));
        req.setTheproductbrand(cutString((String) map.get("theproductbrand"), 30));
        req.setQfshanghuname("031099002115479");
        req.setQfshanghucode("031099002115479");
        req.setModels(cutString((String) map.get("models"), 50));
        req.setModelsdetail(cutString((String) map.get("modelsdetail"), 50));

        String carTotalPrice = convertInt((Double) map.get("car_amount")) + ""; //购车总价
        String shouFuMoney = convertInt((Double) map.get("car_amount")) - convertInt((Double) map.get("loanApproved")) + ""; //首付金额
        String qfShenQingErDu = convertInt((Double) map.get("loanApproved")) + "";
        req.setQfcartotalprice(cutString(String.valueOf(carTotalPrice), 8));
        req.setQfshoufumoney(cutString(String.valueOf(shouFuMoney), 8));
        req.setQfshenqingerdu(cutString(String.valueOf(qfShenQingErDu), 8));
        req.setQfproductcode(cutString((String) map.get("car_no"), 15));
        if (map.get("prolongAA") != null && map.get("insuranceAA") == null) {
            req.setZz_spbh1(cutString((String) map.get("insuranceNo"), 20));
            req.setZz_sqje1(cutString(convertInt((Double) map.get("prolongAA")) + "", 11));
        }else if (map.get("prolongAA") == null && map.get("insuranceAA") != null) {
            req.setZz_spbh1(cutString((String) map.get("insuranceNo"), 20));
            req.setZz_sqje1(cutString(convertInt((Double) map.get("insuranceAA")) + "", 11));
        }else if (map.get("prolongAA") != null && map.get("insuranceAA") != null) {
            req.setZz_spbh1(cutString((String) map.get("insuranceNo"), 20));
            req.setZz_sqje1(cutString(convertInt((Double) map.get("prolongAA")) + "", 11));
            req.setZz_spbh2(cutString((String) map.get("insuranceNo"), 20));
            req.setZz_sqje2(cutString(convertInt((Double) map.get("insuranceAA")) + "", 11));
        }
        //测试核只有延保的情况
//        if (Validator.isNotNull(map.get("insuranceApproved")) && Validator.isNotNull(map.get("insuranceNo"))) {
//            req.setZz_spbh1(cutString((String) map.get("insuranceNo"), 20));
//            req.setZz_sqje1(cutString(convertInt((Double) map.get("insuranceApproved")) + "", 11));
//
//            if ("8aafb8465ecc40bc015effa33efb1bf7".equals(map.get("order_id"))) {
//                req.setZz_spbh2(cutString("249000099007641", 20));
//                req.setZz_sqje2(cutString("5000", 11));
//                req.setZz_spbh3(cutString("369000099007641", 20));
//                req.setZz_sqje3(cutString("3000", 11));
//                req.setZz_spbh4(cutString("129000099007641", 20));
//                req.setZz_sqje4(cutString("6000", 11));
//            }
//        }
        if ("5".equals(map.get("qffenqitype"))) {                      //分期手续费收取方式 1分期，2一次性
            req.setQffenqitype("1");
        } else {
            req.setQffenqitype("2");
        }
        req.setQffenqiqishu(cutString(String.valueOf(map.get("qffenqiqishu")), 2));
        DecimalFormat df = new DecimalFormat("0.00");
        req.setQffenqifeilv(cutString((new BigDecimal(df.format(map.get("qffenqifeilv")))
                                .multiply(new BigDecimal("100")))
                                .toString(), 19));
        req.setQfzichanzhengmingwenjian("2");
        req.setQfgoucheyongtu(cutString((String) map.get("qfgoucheyongtu"), 1));
        req.setChannelcode("QF88");
        req.setPromotionid("NNNNNN");
        req.setCitycode(cutString((String) map.get("citycode"), 4));
        req.setIsrealnamesystem("Y");
        req.setWxgroupphoto("Y");
        req.setPopularizepepolenum(cutString((String) map.get("popularizepepolenum"), 12));
        req.setCardselect("1036001");
        req.setChaifenziduan("&&&&&|0|Y||N|N|Y");
        req.setSource("YCQC");
        req.setApplicationagreementbarcode(cutString((String) map.get("applicationagreementbarcode"), 14));
        req.setPopularizesource("8");
//        req.setPopularizesource("04");  //20180129一帮傻逼的测试
        //他行借记卡，本币自动扣款方式，本币自动扣款账号 三者要么都填，要么都不填
        if (Validator.isNotNull(map.get("tahangjiejika"))&&Validator.isNotNull(map.get("homecurrencywithholdnumber"))){
            req.setTahangjiejika(cutString((String) map.get("tahangjiejika"), 2));
            req.setHomecurrencywithholdtype("T");
            req.setHomecurrencywithholdnumber(cutString((String) map.get("homecurrencywithholdnumber"), 20));
        }else { //应对浦发未开发完毕，做默认值传输
            req.setTahangjiejika("01");
            req.setHomecurrencywithholdtype("T");
            req.setHomecurrencywithholdnumber("0000000000000000");
        }

        req.setIsaccepttelephoneconsultation("1");
        req.setLinkman1mobilephone(cutString((String) map.get("zhixiqinshumobilephone"), 11));
        req.setIs_accept_discount("Y");
        req.setTheproductmodel(cutString((String) map.get("modelsdetail"), 30));
        req.setShenqingrenstation("15");
        if (Validator.isNotNull(map.get("refereeCode"))
                &&Validator.isNotNull(map.get("refereeMobile"))
                &&Validator.isNotNull(map.get("refereeOrgCode"))){
            req.setReferencecode(cutString((String) map.get("refereeCode"),8)); //推荐人代码
            req.setWxreferencecode(cutString((String) map.get("refereeCode"),8)); //推荐人代码
            req.setTuijianrenshoujihaoma(cutString((String) map.get("refereeMobile"), 11)); //推荐人手机号码
            req.setTuijianrenjigoudaima(cutString((String) map.get("refereeOrgCode"), 6)); //推荐人机构代码
        }
        return req;
    }

    private static String cutString(String sourceString, int cutBytes) {
        if (sourceString == null || "".equals(sourceString.trim())) {
            return "";
        }
        int lastIndex = 0;
        boolean stopFlag = false;
        int totalBytes = 0;
        for (int i = 0; i < sourceString.length(); i++) {
            String s = Integer.toBinaryString(sourceString.charAt(i));
            if (s.length() > 8) {
                totalBytes += 2;
            } else {
                totalBytes += 1;
            }
            if (!stopFlag) {
                if (totalBytes == cutBytes) {
                    lastIndex = i;
                    stopFlag = true;
                } else if (totalBytes > cutBytes) {
                    lastIndex = i - 1;
                    stopFlag = true;
                }
            }
        }
        if (!stopFlag) {
            return sourceString;
        } else {
            return sourceString.substring(0, lastIndex + 1);
        }
    }

    private static Integer convertInt(Double a) {
        Integer i = 0;
        if (Validator.isNotNull(a)) {
            i = a.intValue();
        }
        return i;
    }

    public void uploadAlone(String loanOrderId) {
        try {
            Object[] params = {loanOrderId};
            List<Map<String, Object>> listMap = orderDao.getCustomerAppByOrderId(params);
            for (Map<String, Object> map : listMap) {
                String appId = (String) map.get("appId");
                String method = SERVICE_UPLOADAPPLICATION_METHOD;
                UploadAppReq uploadAppReq = buildUploadAppReq(appId, map);
                JSONObject json = (JSONObject) JSONObject.toJSON(uploadAppReq);

                logger.info("订单" + loanOrderId + "------申请件，发送" + json);
                System.out.println("订单" + loanOrderId + "------申请件，发送" + json);

                String requestData = DataEncrypt.initialized().encrypt(method, json, "1");
                String s = SPDBankPAD.sendReq(PropsUtil.getProperty("SPDURL") + Constants.UPLOADAPPLICATION_SERVER, requestData);
                String uploadApplicationResult = DataEncrypt.initialized().deEncrypt(s);

                logger.info("订单" + loanOrderId + "------上传，返回" + uploadApplicationResult);
                System.out.println("订单" + loanOrderId + "------上传，返回" + uploadApplicationResult);

                JSONObject returnJson = JSONObject.parseObject(uploadApplicationResult).getJSONObject("sysres");
                logger.info("保存浦发返回信息 开始：" + loanOrderId);
                System.out.println("保存浦发返回信息 开始：" + loanOrderId);
                saveSPDReturn(appId, map, loanOrderId, returnJson);
                logger.info("保存浦发返回信息 结束：" + loanOrderId);
                System.out.println("保存浦发返回信息 结束：" + loanOrderId);
            }
        } catch (Exception e) {
            Object[] params = {Constants.EXCEPTIONFLAG, loanOrderId};     //Exception 状态
            updateSingleFlag(params);
            setSPDOutputDefault(loanOrderId);
            e.printStackTrace();
        }
    }
}
